package rabbitmq.work;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
 * 工作队列模式-消费者2
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建一个连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USERNAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        //创建一个新的连接
        Connection connection = connectionFactory.newConnection();
        //开启一个通信
        Channel channel = connection.createChannel();
        //声明一个队列，如果队列不存在，则创建，如果队列存在，则不创建
        channel.queueDeclare(Constants.WORK_QUEUE, true, false, false, null);
        //消费消息
        //消费的逻辑
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接受到消息：" + new String(body));
            }
        };
        channel.basicConsume(Constants.WORK_QUEUE, true, consumer);
//        channel.close();
//        connection.close();
    }
}
